package com.fr71.project.dm.controller;

import com.fr71.common.utils.DateUtils;
import com.fr71.framework.aspectj.lang.annotation.Log;
import com.fr71.framework.aspectj.lang.enums.BusinessType;
import com.fr71.framework.web.controller.BaseController;
import com.fr71.framework.web.domain.AjaxResult;
import com.fr71.framework.web.page.TableDataInfo;
import com.fr71.common.utils.poi.ExcelUtil;
import com.fr71.project.dm.domain.PdUser;
import com.fr71.project.dm.service.IPdUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 开发者：https://github.com/devzwy
 * 创建时间：2023-06-26
 * 类描述：用户Controller
 */
@RestController
@RequestMapping("/dm/user")
public class PdUserController extends BaseController {
    
    @Autowired
    private IPdUserService pdUserService;

    /**
     * 查询用户列表
     */
    @PreAuthorize("@ss.hasPermi('dm:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(PdUser pdUser) {
        startPage();
        List<PdUser> list = pdUserService.selectPdUserList(pdUser);
        for (PdUser user : list) {
            long ttt = user.getTotalUsedTime();
            if ("Y".equals(user.getOnlines())) {
                ttt += DateUtils.getNowDate().getTime() - user.getLastConnectTime().getTime();
            }
            
            Triple<Long, Long, Long> timeData = millisecondsToDaysHoursAndMinutes(ttt);
            
            Map<String, Object> params = new HashMap<>();
            params.put("isAuthed", user.getAuthEndTime().before(new Date()) ? "N" : "Y");
            params.put("usedTimeStr", String.format("%02d天%02d小时%02d分钟", 
                    timeData.getFirst(), timeData.getSecond(), timeData.getThird()));
            user.setParams(params);
        }
        return getDataTable(list);
    }
    
    public Triple<Long, Long, Long> millisecondsToDaysHoursAndMinutes(long milliseconds) {
        long totalMinutes = milliseconds / 1000 / 60;
        long days = totalMinutes / (24 * 60);
        long remainingMinutes = totalMinutes % (24 * 60);
        long hours = remainingMinutes / 60;
        long minutes = remainingMinutes % 60;
        return new Triple<>(days, hours, minutes);
    }

    /**
     * 导出用户列表
     */
    @PreAuthorize("@ss.hasPermi('dm:user:export')")
    @Log(title = "用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PdUser pdUser) {
        List<PdUser> list = pdUserService.selectPdUserList(pdUser);
        ExcelUtil<PdUser> util = new ExcelUtil<PdUser>(PdUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    /**
     * 获取用户详细信息
     */
    @PreAuthorize("@ss.hasPermi('dm:user:query')")
    @GetMapping(value = "/{uid}")
    public AjaxResult getInfo(@PathVariable("uid") Long uid) {
        return AjaxResult.success(pdUserService.selectPdUserByUid(uid));
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('dm:user:add')")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PdUser pdUser) {
        return toAjax(pdUserService.insertPdUser(pdUser));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('dm:user:edit')")
    @Log(title = "用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PdUser pdUser) {
        return toAjax(pdUserService.updatePdUser(pdUser));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('dm:user:remove')")
    @Log(title = "用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{uids}")
    public AjaxResult remove(@PathVariable Long[] uids) {
        return toAjax(pdUserService.deletePdUserByUids(uids));
    }
    
    public static class Triple<T, U, V> {
        private final T first;
        private final U second;
        private final V third;
        
        public Triple(T first, U second, V third) {
            this.first = first;
            this.second = second;
            this.third = third;
        }
        
        public T getFirst() { return first; }
        public U getSecond() { return second; }
        public V getThird() { return third; }
    }
}